<template>
  <div class="review-container">
    <div class="filter-container">
      <el-card>
        <div class="filter-header">
          <h3>评价列表</h3>
          <div class="filter-actions">
            <el-select
              v-model="listQuery.hasReply"
              placeholder="回复状态"
              clearable
              style="width: 140px; margin-right: 10px"
              @change="handleFilter"
            >
              <el-option label="全部评价" :value="null" />
              <el-option label="待回复" :value="false" />
              <el-option label="已回复" :value="true" />
            </el-select>
            <el-button type="primary" icon="Search" @click="handleFilter">
              搜索
            </el-button>
            <el-button type="info" icon="Refresh" @click="resetFilter">
              重置
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <el-card class="list-container">
      <el-table
        v-loading="listLoading"
        :data="list"
        border
        stripe
        style="width: 100%"
        highlight-current-row
      >
        <el-table-column label="ID" align="center" width="80">
          <template #default="{ row }">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>

        <el-table-column label="用户信息" align="center" width="200">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar
                :size="40"
                :src="BASE_URL + row.userInfo?.avatar || '/avatar.png'"
              ></el-avatar>
              <div class="user-detail">
                <div class="nickname">{{ row.userInfo?.nickname || '匿名用户' }}</div>
                <div class="date">{{ formatDate(row.createTime) }}</div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="预约信息" align="center" width="240">
          <template #default="{ row }">
            <div v-if="row.reservationInfo">
              <div class="reservation-item">
                <span class="label">预约编号:</span>
                <span class="value">{{ row.reservationInfo.id }}</span>
              </div>
              <div class="reservation-item">
                <span class="label">参观日期:</span>
                <span class="value">{{ row.reservationInfo.visitDate }}</span>
              </div>
              <div class="reservation-item">
                <span class="label">参观时间:</span>
                <span class="value">{{ row.reservationInfo.visitTimeSlot }}</span>
              </div>
              <div class="reservation-item">
                <span class="label">参观人数:</span>
                <span class="value">{{ row.reservationInfo.visitorCount }}人</span>
              </div>
            </div>
            <span v-else>该账号已删除预约记录</span>
          </template>
        </el-table-column>

        <el-table-column label="评分" align="center" width="120">
          <template #default="{ row }">
            <div class="score-display">{{ row.score }}/10</div>
          </template>
        </el-table-column>

        <el-table-column label="评价内容" align="left" min-width="300">
          <template #default="{ row }">
            <div class="review-content">{{ row.content }}</div>
            <div v-if="row.reply" class="review-reply">
              <div class="reply-header">
                <el-icon><Message /></el-icon>
                <span>管理员回复</span>
              </div>
              <div class="reply-content">{{ row.reply }}</div>
              <div class="reply-time">{{ formatDate(row.replyTime) }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="120">
          <template #default="{ row }">
            <el-button
              v-if="!row.reply"
              type="primary"
              size="small"
              @click="handleReply(row)"
            >
              回复
            </el-button>
            <el-button
              v-else
              type="info"
              size="small"
              @click="handleReply(row)"
            >
              修改回复
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="listQuery.page"
          v-model:page-size="listQuery.size"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 回复对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="回复评价"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="reply-dialog-content">
        <div class="original-review">
          <div class="user-info">
            <el-avatar
              :size="30"
              :src="
                BASE_URL + currentRow?.userInfo?.avatar || '/avatar.png'
              "
            ></el-avatar>
            <span class="nickname">{{ currentRow?.userInfo?.nickname || '匿名用户' }}</span>
          </div>
          <div class="review-rating">
            <div class="score-display">{{ currentRow.score }}/10</div>
          </div>
          <div class="review-content">
            {{ currentRow?.content }}
          </div>
        </div>

        <div class="reply-form">
          <el-form ref="replyFormRef" :model="replyForm" :rules="replyRules">
            <el-form-item prop="reply">
              <el-input
                v-model="replyForm.reply"
                type="textarea"
                :rows="4"
                placeholder="请输入回复内容..."
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReply" :loading="replyLoading">
            确认回复
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { reactive, ref, toRefs, onMounted } from 'vue';
import { listReviews, replyReview } from '@/api/review';
import { ElMessage } from 'element-plus';
import { Message } from '@element-plus/icons-vue';
import { BASE_URL } from '@/api/request';
export default {
  name: 'ReviewList',
  components: { Message },
  setup() {
    const user = JSON.parse(localStorage.getItem('adminInfo'));
    const replyFormRef = ref(null);
    
    const state = reactive({
      BASE_URL: BASE_URL,
      list: [], // 评价列表
      total: 0, // 总条数
      listLoading: true, // 列表加载状态
      listQuery: { // 查询参数
        page: 1,
        size: 10,
        hasReply: null
      },
      dialogVisible: false, // 回复对话框是否显示
      currentRow: {}, // 当前选中的评价
      replyForm: { // 回复表单
        reviewId: '',
        adminId: '',
        reply: ''
      },
      replyRules: { // 回复表单验证规则
        reply: [
          { required: true, message: '请输入回复内容', trigger: 'blur' },
          { min: 2, max: 500, message: '回复内容长度在 2 到 500 个字符', trigger: 'blur' }
        ]
      },
      replyLoading: false // 回复提交状态
    });

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
    };

    // 获取评价列表
    const getList = async () => {
      state.listLoading = true;
      try {
        const { data } = await listReviews(state.listQuery);
        state.list = data.records;
        state.total = data.total;
      } catch (error) {
        console.error('Failed to get review list:', error);
        ElMessage.error('获取评价列表失败');
      } finally {
        state.listLoading = false;
      }
    };

    // 处理筛选
    const handleFilter = () => {
      state.listQuery.page = 1;
      getList();
    };

    // 重置筛选
    const resetFilter = () => {
      state.listQuery = {
        page: 1,
        size: 10,
        hasReply: null
      };
      getList();
    };

    // 处理每页数量变化
    const handleSizeChange = (val) => {
      state.listQuery.size = val;
      getList();
    };

    // 处理页码变化
    const handleCurrentChange = (val) => {
      state.listQuery.page = val;
      getList();
    };

    // 处理回复
    const handleReply = (row) => {
      state.currentRow = row;
      state.replyForm.reviewId = row.id;
      state.replyForm.adminId = user.id;
      state.replyForm.reply = row.reply || '';
      state.dialogVisible = true;
    };

    // 提交回复
    const submitReply = async () => {
      if (!replyFormRef.value) return;
      
      await replyFormRef.value.validate(async (valid) => {
        if (!valid) return;
        
        state.replyLoading = true;
        try {
          const res = await replyReview(state.replyForm);
          
          if (res.code === 200) {
            ElMessage.success('回复成功');
            state.dialogVisible = false;
            
            // 更新本地数据
            const index = state.list.findIndex(item => item.id === state.currentRow.id);
            if (index !== -1) {
              state.list[index].reply = state.replyForm.reply;
              state.list[index].adminId = state.replyForm.adminId;
              state.list[index].replyTime = new Date();
            }
          } else {
            ElMessage.error(res.message || '回复失败');
          }
        } catch (error) {
          console.error('Failed to reply review:', error);
          ElMessage.error('回复失败，请重试');
        } finally {
          state.replyLoading = false;
        }
      });
    };

    onMounted(() => {
      getList();
    });

    return {
      ...toRefs(state),
      BASE_URL,
      formatDate,
      handleFilter,
      resetFilter,
      handleSizeChange,
      handleCurrentChange,
      handleReply,
      submitReply,
      replyFormRef
    };
  }
};
</script>

<style lang="scss" scoped>
.review-container {
  padding: 20px;

  .filter-container {
    margin-bottom: 20px;

    .filter-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      h3 {
        margin: 0;
      }

      .filter-actions {
        display: flex;
        align-items: center;
      }
    }
  }

  .list-container {
    .user-info {
      display: flex;
      align-items: center;
      text-align: left;

      .user-detail {
        margin-left: 10px;

        .nickname {
          font-weight: 500;
        }

        .date {
          font-size: 12px;
          color: #999;
        }
      }
    }

    .reservation-item {
      text-align: left;
      margin-bottom: 5px;

      .label {
        color: #666;
        margin-right: 5px;
      }

      .value {
        font-weight: 500;
      }
    }

    .review-content {
      text-align: left;
      margin-bottom: 10px;
      line-height: 1.5;
    }

    .review-reply {
      background-color: #f5f7fa;
      border-radius: 4px;
      padding: 10px;
      margin-top: 10px;
      text-align: left;

      .reply-header {
        display: flex;
        align-items: center;
        margin-bottom: 5px;
        color: #409eff;
        font-weight: 500;

        span {
          margin-left: 5px;
        }
      }

      .reply-content {
        margin-bottom: 5px;
        line-height: 1.5;
        word-break: break-word;
        overflow-wrap: break-word;
        max-width: 100%;
      }

      .reply-time {
        font-size: 12px;
        color: #999;
        text-align: right;
      }
    }
  }

  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }

  .reply-dialog-content {
    .original-review {
      background-color: #f5f7fa;
      border-radius: 4px;
      padding: 15px;
      margin-bottom: 20px;

      .user-info {
        display: flex;
        align-items: center;
        margin-bottom: 10px;

        .nickname {
          margin-left: 10px;
          font-weight: 500;
        }
      }

      .review-rating {
        margin-bottom: 10px;
      }

      .review-content {
        line-height: 1.5;
        word-break: break-word;
        overflow-wrap: break-word;
        max-width: 100%;
      }
    }
  }

  .score-display {
    font-size: 16px;
    font-weight: bold;
    color: #ff9900;
    text-align: center;
  }
}
</style> 